/*
 * Drunk Js
 * Author    :   Drunk
 * Website   :   http://drunkce.com,  http://idrunk.net
 */


D(function(){
var guest = {
	cache : {} ,
	reset : function(para){
		para = D.int(para) ;
		var conelem = guest.form.find('textarea[name=content]') ,
			verelem = guest.form.find('input[name=verify_feedback]') ;

		para & 1 && conelem.val('') ;
		para & 2 && verelem.val('') ;
		para & 4 && guest.form.find('.control img').trigger('click') ;
	} ,
	book : function(){
		guest.form = $('form.comment_form') ;
		if(!guest.form.length)return ;
		guest.setting = D.first(pageConfig.commentSetting) ;
		D.extend(guest.setting, pageConfig) ;
		delete guest.setting.commentSetting ;

		var conelem = guest.form.find('textarea[name=content]') ,
			namelem = guest.form.find('input[name=name]') ,
			verelem = guest.form.find('input[name=verify_feedback]') ,
			noticeTimeout = 2000 ;

		var post = function(){
			var content = conelem.val() ,
				verify = verelem.val() ,
				nickname = namelem.val() ,
				paid = D.int(guest.form.find('input[name=paid]').attr('data-paid')) ;

			if(!guest.setting)return logform.notice("非法操作！", noticeTimeout, ".comment_notice");
			if(content == "" || DC.code(conelem, 1))return logform.notice("请输入评论内容！", noticeTimeout, ".comment_notice");
			if(nickname == "" || DC.code(namelem, 1))return logform.notice("请填写您的称呼！", noticeTimeout, ".comment_notice");
			if(verify == "" || DC.code(verelem, 1))return logform.notice("请输入验证码！", noticeTimeout, ".comment_notice");
			if(DC.code(verelem, 4))return logform.notice("验证码错误！", noticeTimeout, ".comment_notice") ;

			var data = {'paid':paid,'menu_id':guest.setting.menu_id, 'tab':guest.setting.tab, 'iid':guest.setting.iid, 'verify_feedback':verify, 'name':nickname, 'content':content} ;
			guest.bookSave(data, function(data){
				data = data || {} ;
				logform.notice(data.message, noticeTimeout, ".comment_notice", data.status ? 'success' : '', function(){
					guest.reset(data.status ? 7 : 4) ;
				}) ;
				if(data.status)guest.bookList(guest.cache.pages + 1, false) ;
			}) ;
		}

		conelem.bind('click', guest.logdialog) ;
		namelem.bind('click', guest.logdialog) ;
		verelem.bind('click', guest.logdialog) ;
		guest.form.bind('submit', function(){post();return false;}) ;
		guest.bookList() ;
	} ,
	bookSave : function(data, callback){
		var action = guest.form.attr('action') ,
			noticeTimeout = 2000 ;

		$.ajax({
			type : 'POST' ,
			url : action ,
			data : data ,
			cache : false ,
			dataType:"json" ,
			success : callback
		}) ;
	} ,
	bookList : function(page, cache){
		if(!guest.setting.show)return guest.bookListShow() ;
		page = D.int(page) || 1 ;
		cache = D.isUndef(cache) ? true : !!cache ;
		data = {'tab':guest.setting.tab, 'iid':guest.setting.iid} ;
		$.ajax({
			type : 'POST' ,
			url : guest.setting.commentListurl.replace('!page', page) ,
			data : data ,
			cache : cache ,
			dataType:"json" ,
			success : guest.bookListShow
		}) ;
	} ,
	bookListShow : function(data){
		if(!data || !data.message){
			var text = data ? "暂无评论。" : "该内容评论未公开！" ;
			data = data || {} ;
			data.response = '<li class="nodata notopber">' +text+ '</li>' ;
		}

		var listelem = $('.comment_list ul') ;
		guest.cache.pages = D.int(data.message) ;
		listelem.height(listelem.height()).empty().html(data.response) ;
		listelem.children('li').hide().animate({'opacity':'show'}, 'fast', function(){listelem.height('auto');Drunk.control.heightCall();}) ;
		guest.bookListEvent() ;
	} ,
	upit : function(){
		var pli = $(this).parentsUntil('li').parent() ,
			lid = D.int(pli.attr('data-id')) ,
			data = {'tab':'upit', 'iid':lid} ;

		if(D.cookied(lid))return alert('操作失败，您已经顶过该评论！') ;
		guest.bookSave(data, function(data){
			data = data || {} ;
			if(!data.status)return alert('顶操作失败！') ;

			var pups = pli.find('span.upit em') ;
			pups.text(D.int(pups.text()) + 1) ;
			D.cookied(lid, 1) ;
			alert("顶操作成功！") ;
		}) ;
	} ,
	bookReply : function(){
		var pli = $(this).parentsUntil('li').parent() ,
			lid = D.int(pli.attr('data-id')) ,
			lfloor = pli.find('span.floor').text() ,
			lnick = pli.find('span.nick').text().match(/[^[]+(?=\])/)[0] ;

		$("body").animate({scrollTop:guest.form.offset().top - 100}, 'fast', function(){
			var replyButton = $('input[name=paid]').remove() ;
			window.setTimeout(function(){
				replyButton = $('input[name=paid]').remove() ;
				replyButton = $('<input type="button" class="button" value="取消回复 ['+lfloor+' '+lnick+']" name="paid" data-paid="'+lid+'" />') ;
				guest.form.find('span.buttons').prepend(replyButton) ;
				replyButton.bind('click', function(){$(this).remove()}) ;
			}, 200) ;
		});
	} ,
	bookListEvent : function(){
		var listpager = $('.comment_list span.clpager span[data-page]') ,
			li = $('.comment_list li') ;
			upit = li.find('span.upit') ,
			replyit = li.find('span.replyit') ;

		listpager.bind('click', function(){guest.bookList(D.int($(this).attr('data-page')) || 1) ;}) ;
		upit.bind('click', guest.upit) ;
		replyit.bind('click', guest.bookReply) ;
	} ,
	logdialog : function(){
		if(!guest.cache.cancelLogin)logform.dialog({cancel : function(){
			if(confirm("非登录状态下的发言将会进入审核状态，您确定要继续吗？"))guest.cache.cancelLogin = 1 ;
		}, jump : 0}) ;
	} ,
	init : function(){
		logform.loadvarscript(function(){
			guest.book() ;
			DC.init(guest.form) ;
		}) ;
	}
}

var appo = {
	config : {} ,
	dialog : function(config){
		config = config || {} ;
		var form = '<form method="post" action="/index.php/313-druson~1.html"><table><tr><th><em>*</em> 电话：</th><td><input class="input" name="phone" drunk="input=#999,联系电话" value="'+D.ifempty(config['phone'], '')+'" /></td></tr>' +
			'<tr><th>称呼：</th><td><input class="input" name="name" drunk="input=#999,您的称呼" /></td></tr>' +
			'<tr><th>备注：</th><td><textarea name="memo">'+D.ifempty(config['memo'], '')+'</textarea></tr>' +
			'<tr><th><em>*</em> 验证码：</th><td><input name="verify_reservation" class="input" drunk="variable=verify,\'{ w:80,h:24,c:4}\',;input=#999,点击图片可以刷新" autocomplete="off" /></td></tr>' +
			'<tr><th>&nbsp;</th><td><input type="submit" class="button" value="提交" /><input type="button" class="button" value="取消" /></td></tr>' +
			'</table></form>' ;

		Drunk.extend(appo.config, config) ;
		var dialog = logform.yo()($(form)) ;
		logform.title({416:"免费预算方案预约",417:"装修预约",418:"设计预约"}[appo.config.cid]) ;
		dialog.find('form').bind('submit', appo.submit) ;
		dialog.find('input[type=button]').bind('click', logform.destroy) ;
		D(function(){DC.init(dialog) ;}) ;
	} ,
	submit : function(){
		var elem , f = $(this) ,
			action = f.prop('action') ;
			json = {cid:appo.config.cid, appointment_id:appo.config.appointment_id} ,
			elems = f.find('[name]') ;

		elems.each(function(i,e){
			elem = $(e) ;
			json[elem.prop('name')] = elem.val() ;
		}) ;
		if(D.empty(json.phone) || DC.code(f.find('[name=phone]'), 1))return !!logform.notice("请填写联系电话！", 3000) ;
		if(D.empty(json.verify_reservation) || DC.code(f.find('[name=verify_reservation]'), 1) || json.verify_reservation.length !== 4)return !!logform.notice("验证码错误！", 3000) ;

		$.ajax({
			type:'POST',
			url:action,
			data:json,
			dataType:"json",
			success : function(data){
				if(!data || !data.status){
					if(data)logform.notice(data.message, 3000) ;
					return logform.verifyRefresh() ;
				}
				logform.notice(data.message, 4000, 0, 'success', logform.destroy) ;
			}
		}) ;

		return false ;
	} ,
	init : function(){
		logform.loadvarscript(function(){
			$(".appointment").bind("click", function(){
				var	elem = $(this),
					callback = elem.attr('data-callback') ,
					setting = elem.attr('data-setting').match(/^(\d+)(?:,(\d+))?$/) ;
	
				eval("callback = " + callback + ";")
				appo.config.cid = D.int(setting[1]) ;
				appo.config.appointment_id = D.int(setting[2]) ;

				config = $.isFunction(callback) ? callback(appo) : {} ;
				appo.dialog(config) ;
			}) ;
		}) ;
	}
}

guest.init() ;
appo.init() ;
logform.init();
// logform.message() ;
window.alooat = 1;
}) ;

D.extend(DC, {
	commentId : 0,
	comment : function(elem,tab,iid,method,count,length){
		if(!DC.cache.comment)DC.cache.comment = {} ;
		DC.cache.comment[DC.commentId] = {param:{id:DC.commentId,tab:tab,iid:iid,method:method,count:count,length:length},elem:elem} ;
		if(!DC.endCalls.has(DC.commentCall))DC.endCalls.add(DC.commentCall);
		DC.commentId ++;
	},
	commentCall : function(){
		var config = DC.cache.comment,
			i, data = {};

		data.config=[];
		for(i in config)data.config[data.config.length] = config[i].param;

		$.ajax({
			url:'/index.php?s=/comments-druson~1.html',
			type:'POST',
			dataType:"json",
			data:data,
			success: function(data){DC.commentShow(data);}
		});
	},
	commentShow : function(data){
		var config = DC.cache.comment,
			i, conf, method, j, elem, commentem;

		for(i in config){
			conf = config[i];
			method = D.int(conf.param.method);
			if(method & 1){
				if(D.empty(data[i]) || !$.isArray(data[i])){
					conf.elem.text('暂无评论');
					continue;
				}
				for(j=0;j<data[i].length;j++){
					elem = j ? conf.elem.clone().insertAfter(conf.elem) : conf.elem;
					commentem = method & 2 ? '<a href="' +data[i][j].url+ '">' +data[i][j].content+ '</a>' : data[i][j].content;
					elem.html(commentem);
				}
			}else{
				conf.elem.text(D.int(data[i]));
			}
		}
	}
}) ;